package Data;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

public class ReturnGoodRecordOperator implements IDataReader,IDataUpdate,IDataWriter{

	ArrayList<ReturnGoodRecord> returnGoodRecordDataList = new ArrayList<ReturnGoodRecord>();
	String filename = "D:\\ReturnGoodRecord.txt";
	
	public ReturnGoodRecordOperator(){
		try{
			BufferedReader bf = new BufferedReader(new FileReader(filename));
			ReturnGoodRecord rgr = null;
			String data = "";
			String record[] = null;
			while((data = bf.readLine()) != null){
				if(data.trim().equals("")){
					continue;
				}
				record = splitText(data);
				rgr = new ReturnGoodRecord(Integer.parseInt(record[0]),Integer.parseInt(record[1]),record[2],Double.parseDouble(record[3]),Double.parseDouble(record[4]),Double.parseDouble(record[5]),record[6],Integer.parseInt(record[7]));
				returnGoodRecordDataList.add(rgr);
			}	
		}catch(IOException e){
			e.printStackTrace();
		}
	}
	
	public String[] splitText(String s){
		String[] data = s.split(",");
		return data;
	}
	
	public void saveData(int goodID,String goodName,double returnNumber,double price,double specialPrice,String returnDate,int saleID){
		String s = "";
		String s1 = "\r\n";
		try{
			BufferedWriter writer = new BufferedWriter(new FileWriter(new File(filename),true));
			s = getNextReturnID() + "," + goodID + "," + goodName + "," + returnNumber + "," + price + "," + specialPrice + "," + returnDate + "," + saleID;
			writer.write(s);
			writer.write(s1);
			writer.close();
		}catch(IOException ex){
			ex.printStackTrace();
		}
	}
	
	public ArrayList<ReturnGoodRecord> readReturnGoodRecordBySaleID(int ID){
		ArrayList<ReturnGoodRecord> returnGoodRecordDataList1 = new ArrayList<ReturnGoodRecord>();
		for(ReturnGoodRecord rgr:returnGoodRecordDataList){
			if(rgr.getThisSaleID() == ID){
				returnGoodRecordDataList1.add(rgr);
			}
		}
		return returnGoodRecordDataList1;
	}
	
	@Override
	public void saveData() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void startUpdate() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public ReturnGoodRecord readDataByID(int id) {
		// TODO Auto-generated method stub
		return null;
	}
	
	public int getNextReturnID(){
		int i = 0;
		try{
			BufferedReader bf = new BufferedReader(new FileReader(filename));
			String data = "";
			String record[] = null;
			while((data = bf.readLine()) != null){
				if(data.trim().equals("")){
					continue;
				}
				record = splitText(data);
				i = Integer.parseInt(record[0]);
			}	
		}catch(IOException ex){
			ex.printStackTrace();
		}
		i = i + 1;
		return i;
	}

}
